package com.nowcoder.community.community.config;

import com.nowcoder.community.community.quartz.AlphaJob;
import com.nowcoder.community.community.quartz.PostScoreRefreshJob;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

// 配置 --> 数据库 --> 调用
// 作用: 只有第一次调用时被读取到, 其封装的信息会被初始到数据库中, 以后每次quartz访问数据库调度任务, 而不再访问此配置文件
@Configuration
public class QuartzConfig {

    /**
     * FactoryBean可简化Bean的实例化过程:
     *      1. Spring通过FactoryBean封装了Bean的实例化过程.
     *      2. 它会将FactoryBean装配到Spring容器里.
     *      3. 然后将FactoryBean注入给其他的Bean.
     *      4. 该Bean得到的是FactoryBean所管理的对象实例
     */

    // 配置JobDetail
    // @Bean
    public JobDetailFactoryBean alphaJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(AlphaJob.class);
        factoryBean.setName("alphaJob");
        factoryBean.setGroup("alphaJobGroup");
        factoryBean.setDurability(true);// 设置任务长久保存
        factoryBean.setRequestsRecovery(true);// 设置任务可恢复
        return factoryBean;
    }

    // 配置Trigger(SimpleTriggerFactoryBean, CronTriggerFactoryBean)
    // @Bean
    public SimpleTriggerFactoryBean alphaTrigger(JobDetail alphaJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(alphaJobDetail);// 设置任务的JobDetail
        factoryBean.setName("alphaTrigger");
        factoryBean.setGroup("alphaTriggerGroup");
        factoryBean.setRepeatInterval(3000);// 设置任务的执行频率(每三秒执行一次)
        factoryBean.setJobDataMap(new JobDataMap());// 设置存储Job的状态
        return factoryBean;
    }

    /**
     * 刷新帖子分数的任务
     */
    @Bean
    public JobDetailFactoryBean postScoreRefreshJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(PostScoreRefreshJob.class);
        factoryBean.setName("postScoreRefreshJob");
        factoryBean.setGroup("communityJobGroup");
        factoryBean.setDurability(true);
        factoryBean.setRequestsRecovery(true);
        return factoryBean;
    }

    /**
     * 刷新帖子分数的配置
     */
    @Bean
    public SimpleTriggerFactoryBean postScoreRefreshTrigger(JobDetail postScoreRefreshJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(postScoreRefreshJobDetail);
        factoryBean.setName("postScoreRefreshTrigger");
        factoryBean.setGroup("communityTriggerGroup");
        factoryBean.setRepeatInterval(1000 * 60 * 5);
        factoryBean.setJobDataMap(new JobDataMap());
        return factoryBean;
    }

}
